﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using Eksponent.CropUp.Client;
using umbraco.cms.businesslogic.media;

namespace Eksponent.CropUp.Umbraco.Xslt
{
    public class XsltHelpers
    {
        static string ById(int mediaId, Func<string, string> action)
        {
            var m = new Media(mediaId);
            if (m.Id != 0)
            {
                return action("" + m.getProperty("umbracoFile").Value);
            }

            return "";
        }

        public static string UrlByMediaId(int mediaId, string args)
        {
            return ById(mediaId, src => Url(src, args));
        }

        public static string Url(string path, string args)
        {
            var imageArgs = ImageSizeArguments.Parse(args);
            return CropUp.GetUrl(path, imageArgs);
        }


        public static string ResponsiveByMediaId(int mediaId, string args, string cssClass, string style, string id)
        {
            return ById(mediaId, src => Responsive(src, args, cssClass, style, id));
        }

        static Regex _progressiveArgsParser = new Regex(@"p(rogressive)?(?<Step>[0-9]+)(?<NoZoom>N)?", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        public static string Responsive(string path, string args, string cssClass, string style, string id)
        {
            if (args.Equals("server", StringComparison.InvariantCultureIgnoreCase))
            {
                args = "P0Z";
            }

            var m = _progressiveArgsParser.Match(args);
            if (m.Success)
            {
                return CropUpHtml.CropUpResponsive(path,
                    upscaleStep: int.Parse(m.Groups["Step"].Value),
                    zoom: !m.Groups["NoZoom"].Success,
                    style: EmptyToNull(style), cssClass: EmptyToNull(cssClass), id: EmptyToNull(id)).ToString();
            }
            var imageArgs = ImageSizeArguments.Parse(args);

            return CropUpHtml.CropUpResponsive(path,
                imageArgs.Width, imageArgs.Height, imageArgs.CropAlias, imageArgs.Zoom,
                    EmptyToNull(style), EmptyToNull(cssClass), EmptyToNull(id)).ToString();
        }

        static string EmptyToNull(string s)
        {
            return string.IsNullOrEmpty(s) ? null : s;
        }

        //public static string Responsive(string path, int )
    }
}
